from json import load as jsonloads
from jili.core.printlog import print
from sys import path as ppath
from os.path import join as pathjoin
from os.path import exists as pathexists
from os.path import abspath
import sys,os
from jili.tool.pcinfo import get_pcname
from jili.tool.state import data_url
from copy import deepcopy
def load_config_json(name="config.json"):
    p=os.path.dirname(name)
    if p=="":
        url=abspath(pathjoin(os.path.dirname(sys.argv[0]),name))
    else:
        url=name
    a = {}
    if os.path.exists(url):
        with open(url, 'r', encoding='utf-8') as fp:
            a=jsonloads(fp)
    return a

def load_config_json_bypcname(name="config_bt.json"):
    pcname=get_pcname()
    c=load_config_json(name)
    if pcname in c.keys():
        a=c[pcname]
        return a
    elif "default" in c.keys():
        a = c["default"]
        return a
    else:
        return {}
def load_sys_config_json_bypcname(name="config_bt"):
    pcname=get_pcname()
    url = os.path.join(data_url, name+".json")
    c=load_config_json(url)
    if pcname in c.keys():
        return c[pcname]
    else:
        return {}
class Config():
    def __init__(self):
        self.config={}
        self.root=abspath(pathjoin(__file__, "../../../config"))
        f = pathjoin(self.root, "atsconfig.json")
        if pathexists(f):
            with open(f, 'r') as load_f:
                load_dict = jsonloads(load_f)
                self.update(load_dict)
    def loadbyfile(self,file="",name=""):
        f= ppath[0]
        if file!="":
            f=file
        else:
            if name!="":
                f=pathjoin(f,name)
            else:
                f=pathjoin(f,"config.json")
        if pathexists(f):
            with open(f, 'r') as load_f:
                load_dict = jsonloads(load_f)
                self.update(load_dict)
        return self.config
    def loadbydb(self,arg):
        return self.config
    def update(self,config):
        updateconfig(self.config,config)

config=Config()
def updateconfig(config0,config):
    for k,v in config.items():
        if isinstance(v,dict):
            if k in config0.keys():
                if isinstance(config0[k],dict):
                    config1 = config0[k]
                else:
                    config1 = {}
                    config0[k] = config1
            else:
                config1 = {}
                config0[k] = config1
            updateconfig(config1,v)
        else:
            config0[k]=v
if __name__=="__main__":
    # a={"a":1,"b":{"a":1,"b":[1,2,3]}}
    # b={"c":2,"b":{"b":[1,2],"c1":{"a":1}}}
    # updateconfig(a,b)
    print(os.path.dirname(sys.argv[0]))